// pages/Meetinginvitation/Meetinginvitation.js
const $api = require('../../utils/api.js').API;
var app = getApp()
import drawQrcode from '../../utils/weapp.qrcode.min.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件所需的参数
    navbarData: {
      havebg: 1, //1表示显示    0表示不显示
      out: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '邀请人详情', //导航栏 中间的标题
      bg: '#fff', //导航背景
    },
    info: {},
    meetlist: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let _this = this
    $api.getmeetinglists({
      login_token: wx.getStorageSync('login_token'),
    }).then((res) => {
      console.log(res)
      _this.setData({ meetlist: res.data.data })
    })
  },
  //弹框
  showModal(e) {
    var _this = this;
    _this.setData({
      modalName: e.currentTarget.dataset.target,
      tkinfo: {}
    })

  },
  meetclick(e) {
    console.log(e)
    this.setData({ tkinfo: e.currentTarget.dataset.item, })
  },
  okModal() {
    let _this = this
    let tkinfo = _this.data.tkinfo
    if (!tkinfo.id) {
      wx.showToast({
        title: '请选择会议主题',
        icon: 'none',
        duration: 2000
      })
      return
    }
    $api.getmeetinginfo({
      login_token: wx.getStorageSync('login_token'),
      meeting_id: tkinfo.id,
    }).then((res) => {
      console.log(res)
      _this.setData({ info: res.data.data ,modalName:'',tkinfo:{}})
      _this.wxcode(res.data.data)
    })
  },
  wxcode(item){
    var _this = this;
    // return
    //二维码
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    var _this = this;
    let index = item.erwm_img.indexOf("=")
    var url = item.erwm_img.substring(index + 1,item.erwm_img.length)
    url = decodeURIComponent(url)
    console.log(url,88)
    var qrcode_width = 170; //二维码大小
    var qrcode_background = "#FFFFFF"; //二维码背景颜色，默认值白色。颜色太深容易扫不出来，不兼容。颜色越淡越好。
    var qrcode_foreground = "#000000"; //二维码前景色，默认值黑色
    var qrcode_url = url
    console.log(url,132)
    //  var qrcode_url = 'https://newone.tjyunsen.com/live/'
    //生成二维码
    drawQrcode({
      width: qrcode_width,
      height: qrcode_width,
      x: 20,
      y: 20,
      canvasId: 'logoQRCode',
      text: qrcode_url,
      background: qrcode_background, //二维码背景颜色，默认值白色
      foreground: qrcode_foreground, //二维码前景色，默认值黑色
      correctLevel: 2, //非必须，二维码纠错级别，默认值为高级，取值：{ L: 1, M: 0, Q: 3, H: 2 }
      callback(e) {
        console.log('e: ', e)
      }
    })
    // console.log(132)
    wx.downloadFile({
      url: 'https://jiujinimg.tjnanguyi.com/zhenyuanqi/huiyiyaoyue.png',
      success(res) {
        console.log(res,1111)
        //加logo
        _this.drawImg(res.tempFilePath, qrcode_width + 75, 'logoQRCode', qrcode_background, qrcode_foreground); //打上LOGO
      }
    })
    // 获取手机号
    // var phone = wx.getStorageSync('mobile')
    // var mobile = phone.substring(0, 3) + '****' + phone.substring(7);
    // var nickname = wx.getStorageSync('nickname')
    // _this.setData({
    //   nickname: nickname
    // })
    //将加完logo的二维码生成图片
    var qrCode = setInterval(function () {
      clearInterval(qrCode)
      //生成图片
      wx.canvasToTempFilePath({
        width: 250,
        height: 250,
        destWidth: 250,
        destHeight: 250,
        canvasId: 'logoQRCode',
        success: function (res) {
          console.log(132)
          var tempFilePath = res.tempFilePath;
          _this.setData({
            qrCodeImg: tempFilePath,
            qrCodeState: true
          }) 
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }, 300)

    //生成海报
    var poster = setInterval(function () {
      console.log(_this.data.qrCodeImg, _this.data.nickname,66)
      if (_this.data.qrCodeState) {
        console.log(11)
        clearInterval(poster)
        _this.onCanvas(_this.data.qrCodeImg)
      }
    }, 400)
  },
  //查看图片
  onUrl() {
    let _this = this
    wx.getImageInfo({
      src: _this.data.tempFilePath,
      success: function (res) {
        console.log(res)
        var path = res.path;
        wx.saveImageToPhotosAlbum({
          filePath: path,
          success(cres){
            console.log(cres)
            wx.showToast({
              title: '保存图片成功',
            })
          },
          fail(err){
            if(err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response"){
              // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
              wx.showModal({
                title: '提示',
                content: '需要您授权保存相册',
                showCancel: false,
                success: modalSuccess => {
                  wx.openSetting({
                    success(settingdata) {
                      console.log("settingdata", settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限成功,再次点击图片即可保存',
                          showCancel: false,
                        })
                      } else {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限失败，将无法保存到相册哦~',
                          showCancel: false,
                        })
                      }
                    },
                    fail(failData) {
                      console.log("failData", failData)
                    },
                    complete(finishData) {
                      console.log("finishData", finishData)
                    }
                  })
                }
              })
            }else{
              wx.showToast({
                icon: 'none',
                title: '保存图片失败',
              })
            }
            
          }
        })
      }
    })
    // wx.saveImageToPhotosAlbum({
    //   filePath: this.data.tempFilePath,
    //   success(res){
    //     wx.showToast({
    //       title: '保存图片成功',
    //     })
    //   },
    //   fail(res){
    //     wx.showToast({
    //       title: '保存图片失败',
    //     })
    //   }
    // })
    // wx.previewImage({
    //   urls: [this.data.tempFilePath],
    //   current: this.data.tempFilePath
    // })
  },
  //生成海报
  onCanvas(ercode, mobiles) {
    var _this = this;
    let info = _this.data.info
console.log(info)
    var ctx = wx.createCanvasContext('firstCanvas')
    wx.downloadFile({
      url: 'https://ttttest.boyamankeji.com/static/theme/img/huiyiyaoyue.png',
      success(res) {
        console.log(556,111)
        const canvasWidth = 345;
        const centerX = canvasWidth / 2;
        ctx.drawImage(res.tempFilePath, 0, 0, 343, 348)
        ctx.draw(true)
        ctx.drawImage(ercode, 100, 80, 210, 210)
        ctx.setFontSize(15)
        ctx.fillStyle = 'rgba(0, 0, 0, 1)';
        ctx.setTextAlign('center')
        ctx.fillText(info.title, centerX,255)
        ctx.setTextAlign('center')
        ctx.fillText(info.user_name, centerX,275)
        ctx.draw(true)
        

        setTimeout(function () {
          //生成图片
          wx.canvasToTempFilePath({
            width: 343,
            height: 343,
            destWidth: 343,
            destHeight: 343,
            canvasId: 'firstCanvas',
            success: function (res) {
              var tempFilePath = res.tempFilePath;
              console.log(556)
              wx.hideLoading();
              _this.setData({
                tempFilePath: tempFilePath,
              })
            },
            fail: function (res) {
              console.log(res);
            }
          });
        }, 300)
      }
    })






  },
  //加logo
  drawImg(src, width, canvas, qrcode_background, qrcode_foreground) {
    var imgSize = Math.round(width / 8);
    var imgPos = Math.round(width / 9 * 4) - 38;
    var imgPosFix = Math.round(width / 120);
    const ctx2 = wx.createCanvasContext(canvas);
    //ctx2.strokeStyle = '#fff';
    //ctx2.lineWidth = 4;
    //ctx.globalAlpha = 0.8;
    ctx2.globalAlpha = 1; //透明度
    //ctx2.lineCap = "round";
    //ctx2.lineJoin = "round";
    ctx2.beginPath();
    ctx2.setStrokeStyle(qrcode_background); //'#fff'
    ctx2.setLineWidth(4);
    ctx2.setLineCap('round');
    ctx2.setLineJoin('round');
    ctx2.moveTo(imgPos - imgPosFix, imgPos - imgPosFix);
    //ctx2.moveTo(imgPos, imgPos);    
    ctx2.lineTo(imgPos + imgSize + imgPosFix, imgPos - imgPosFix); //上边
    ctx2.lineTo(imgPos + imgSize + imgPosFix, imgPos + imgSize + imgPosFix); //右边
    ctx2.lineTo(imgPos - imgPosFix, imgPos + imgSize + imgPosFix); //下边
    ctx2.lineTo(imgPos - imgPosFix, imgPos - imgPosFix); //左边    
    ctx2.stroke();
    ctx2.closePath();

    ctx2.beginPath();
    ctx2.setStrokeStyle(qrcode_foreground); //'#000'
    ctx2.setLineWidth(1);
    ctx2.setLineCap('round');
    ctx2.setLineJoin('round');
    ctx2.moveTo(imgPos - imgPosFix, imgPos - imgPosFix);
    //ctx2.moveTo(imgPos, imgPos);    
    // ctx2.lineTo(imgPos + imgSize + imgPosFix, imgPos - imgPosFix);//上边
    // ctx2.lineTo(imgPos + imgSize + imgPosFix, imgPos + imgSize + imgPosFix);//右边
    // ctx2.lineTo(imgPos - imgPosFix, imgPos + imgSize + imgPosFix);//下边
    // ctx2.lineTo(imgPos - imgPosFix, imgPos - imgPosFix);//左边    
    ctx2.stroke();
    ctx2.closePath();

    ctx2.drawImage(src, imgPos - 1, imgPos - 1, imgSize + 2, imgSize + 2);
    //ctx2.beginPath();
    ctx2.draw(true);
    this.setData({
      logoState: true
    })
  },
  gonumber(){
    let info = this.data.info
    if(!info.meeting_id){
      return
    }
    wx.navigateTo({
      url: '/pages/Meetingnumber/Meetingnumber?meeting_id=' + info.meeting_id,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})